package v1

import (
	"fmt"
	"net/http"
	"regexp"
	"strconv"
	"strings"
	"wlblog/src/model"
	"wlblog/src/utils/errmsg"

	"github.com/gin-gonic/gin"
)

// 查询用户是否存在
func UserExist(c *gin.Context) {

}

// 添加用户
func AddUser(c *gin.Context) {
	var user model.User
	var code int
	// 绑定请求数据
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": errmsg.ERROR,
			"msg":  err.Error(),
		})
		return
	}
	// 验证数据
	user.UserName = strings.TrimSpace(user.UserName)
	if ok, _ := regexp.MatchString("^[a-zA-Z][a-zA-Z0-9_]{3,19}$", user.UserName); !ok {
		code = errmsg.USER_NAME_FORMAT_WRONG
	} else if len(user.Password) < 8 || len(user.Password) > 16 {
		code = errmsg.PASSWORD_LENGTH_WRONG
	}

	if code > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg":  errmsg.ErrMsg(code),
		})
		return
	}

	code = user.Create()
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  errmsg.ErrMsg(code),
	})

}

// 查询单个用户
func UserInfo(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		fmt.Printf("请求的用户ID不正确: %v\n", err)
		code := errmsg.USER_ID_FORMAT_WRONG
		c.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg":  errmsg.ErrMsg(code),
		})
		return
	}

	user, code := model.GetUser(uint(id))
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  errmsg.ErrMsg(code),
		"data": &user,
	})
}

// 查询用户列表
func UserList(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pagesize"))
	currPage, _ := strconv.Atoi(c.Query("currpage"))
	userName := c.Query("username")

	fmt.Printf("userName: %s, pageSize: %d, currPage: %d\n",
		userName, pageSize, currPage)

	users, total := model.GetUsers(userName, pageSize, currPage)
	code := errmsg.SUCCE
	c.JSON(http.StatusOK, gin.H{
		"code":  code,
		"data":  users,
		"total": total,
		"msg":   errmsg.ErrMsg(code),
	})
}

// 编辑用户
func EditUser(c *gin.Context) {

}

// 删除用户
func DelUser(c *gin.Context) {

}
